package com.martinwj.camera2demo.module;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.Face;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.AudioManager;
import android.media.Image;
import android.media.ImageReader;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.ThumbnailUtils;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.martinwj.camera2demo.MainActivity;
import com.martinwj.camera2demo.R;
import com.martinwj.camera2demo.adapter.FuncHorizontalScrollAdapter;
import com.martinwj.camera2demo.ui.AutoFitTextureView;
import com.martinwj.camera2demo.ui.FuncHorizontalScrollView;
import com.martinwj.camera2demo.ui.PictureActivity;
import com.martinwj.camera2demo.utils.ErrorDialog;
import com.martinwj.camera2demo.utils.ImageUtils;
import com.martinwj.camera2demo.utils.MediaFunc;
import com.martinwj.camera2demo.utils.PermissionDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;


public class CameraFragment extends Fragment
        implements View.OnClickListener, ActivityCompat.OnRequestPermissionsResultCallback {

    private static final int SENSOR_ORIENTATION_DEFAULT_DEGREES = 90;
    private static final int SENSOR_ORIENTATION_INVERSE_DEGREES = 270;
    /**
     * 从屏幕旋转到JPEG方向的转换。
     */
    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
    private static final SparseIntArray INVERSE_ORIENTATIONS = new SparseIntArray();

    private static final int REQUEST_CAMERA_PERMISSION = 1;
    private static final int REQUEST_VIDEO_PERMISSIONS = 1;
    private static final String FRAGMENT_DIALOG = "dialog";

    static {
        ORIENTATIONS.append(Surface.ROTATION_0, 90);
        ORIENTATIONS.append(Surface.ROTATION_90, 0);
        ORIENTATIONS.append(Surface.ROTATION_180, 270);
        ORIENTATIONS.append(Surface.ROTATION_270, 180);
    }
    static {
        INVERSE_ORIENTATIONS.append(Surface.ROTATION_0, 270);
        INVERSE_ORIENTATIONS.append(Surface.ROTATION_90, 180);
        INVERSE_ORIENTATIONS.append(Surface.ROTATION_180, 90);
        INVERSE_ORIENTATIONS.append(Surface.ROTATION_270, 0);
    }

    //缩略图参数
//    private Context sContext = getContext();
//    private static final String[] STORE_IMAGES = {
//            MediaStore.Images.Thumbnails._ID,
//    };
    //拍照按钮参数
    private ImageView iv_pictures;
    //录像参数
    private MediaRecorder mMediaRecorder;
    private int mRecordingVideo = 3; // 1:开始录像  2：停止录像  3：拍照
    private String mNextVideoAbsolutePath;
    private CameraCaptureSession mPreviewSession;
    private int mCaptureRate = 30;
    //计时器
    Chronometer time;

    //ui控件参数
    private ImageView iv_info;
    private ImageView iv_flash;
    private ImageView iv_setting;
    private ImageView iv_change;
    private TextView tv_delayed;
    private TextView tv_continuous;
    private TextView tv_pictures;
    private TextView tv_videotapes;
    private TextView tv_slowMotion;

    //闪关灯标识
    private int mFlash = 0;
    // 前后置摄像头切换参数，0：后置， 1：前置。
    private int mCameraState = 0;
    // 分辨率：0:原始分辨率  1：分辨率1456x1456   2：分辨率480x640   3：分辨率720x1280
    private static int mRatio = 0;
    // 水印标志： 0: 不添加水印   1：添加水印
    private int mWatermark = 0;
    // 水印字
    TextView textView;
    // 拍照倒计时
    private  TextView tv_timer;

    private Size[] sizeArr;

    /**
     * TAG
     */
    private static final String TAG = "CameraFragment";

    /**
     * 相机状态：显示相机预览。
     */
    private static final int STATE_PREVIEW = 0;

    /**
     * 相机状态：等待焦点被锁定。
     */
    private static final int STATE_WAITING_LOCK = 1;

    /**
     * 相机状态：等待曝光为预拍摄状态。
     */
    private static final int STATE_WAITING_PRECAPTURE = 2;

    /**
     * 相机状态：等待曝光状态为预拍摄以外的状态。
     */
    private static final int STATE_WAITING_NON_PRECAPTURE = 3;

    /**
     * 相机状态：已拍摄照片。
     */
    private static final int STATE_PICTURE_TAKEN = 4;

    /**
     * Camera2 API保证的最大预览宽度
     */
    private static final int MAX_PREVIEW_WIDTH = 1920;

    /**
     * Camera2 API保证的最大预览高度
     */
    private static final int MAX_PREVIEW_HEIGHT = 1080;

    /**
     * TextureView.SurfaceTextureListener 处理一个 TextureView
     */
    private final TextureView.SurfaceTextureListener mSurfaceTextureListener
            = new TextureView.SurfaceTextureListener() {

        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture texture, int width, int height) {
            openCamera(width, height);
        }

        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int width, int height) {
            configureTransform(width, height);
        }

        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) {
            return true;
        }

        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture texture) {
        }

    };

    /**
     * 缩略图
     */
    private static ImageView mPicture_tv;
    /**
     * Bitmap  压缩存储缩略图 往往主要用来处理海量数据
     */
    private static Bitmap picture;

    /**
     * 自定义接收消息的线程Handler  重写里面的handleMessage（）方法   主要作用是对拿到的信息进行处理
     */
    @SuppressLint("HandlerLeak")
    private static final Handler pictureHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 1){
                mPicture_tv.setImageBitmap(picture);
            }
        }
    };

    /**
     * 当前相机的ID
     */
    private String mCameraId;

    /**
     * 自定义AutoFitTextureView控件用于相机预览
     */
    private AutoFitTextureView mTextureView;

    /**
     * 用于相机预览的  CameraCaptureSession获取数据会话
     */
    private CameraCaptureSession mCaptureSession;

    /**
     *  摄像头设备类  一个CameraDevice对应一个摄像头设备
     */
    private CameraDevice mCameraDevice;

    /**
     * 相机预览的尺寸大小
     */
    private Size mPreviewSize;

    /**
     *
     * 摄像头的状态接口回调 主要是负责摄像头的开启/断开/异常/销毁，当更改其状态时，调用CameraDevice.StateCallback
     * 当 CameraManager 打开指定的id的摄像头时需要添加这个回调
     *
     */
    private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {

        @Override
        public void onOpened(@NonNull CameraDevice cameraDevice) {
            // 这个方法在摄像机打开时被调用。我们从这里开始相机预览。
            mCameraOpenCloseLock.release();
            mCameraDevice = cameraDevice;
            createCameraPreviewSession();// 调用createCameraPreviewSession()来开启预览
        }

        @Override
        public void onDisconnected(@NonNull CameraDevice cameraDevice) {
            mCameraOpenCloseLock.release();
            cameraDevice.close();
            mCameraDevice = null;
        }

        @Override
        public void onError(@NonNull CameraDevice cameraDevice, int error) {
            mCameraOpenCloseLock.release();
            cameraDevice.close();
            mCameraDevice = null;
            Activity activity = getActivity();
            if (null != activity) {
                activity.finish();
            }
        }

    };

    /**
     * 用于运行不应该阻塞UI的任务的附加线程。
     */
    private HandlerThread mBackgroundThread;

    /**
     * 用于在后台运行任务 Handler
     */
    private Handler mBackgroundHandler;

    /**
     * 处理静态图像捕获 图片获取器
     */
    private ImageReader mImageReader;

    /**
     * 图片的输出文件。
     */
    private File mFile;
    private  static long  begin;

    /**
     * 这是ImageReader的回调对象。当准备好保存静止图像时，将调用“onImageAvailable”。
     */
    private final ImageReader.OnImageAvailableListener mOnImageAvailableListener
            = new ImageReader.OnImageAvailableListener() {

        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onImageAvailable(ImageReader reader) {
            mBackgroundHandler.post(new ImageSaver(reader.acquireNextImage(), mFile, mCameraState, mRatio, mWatermark, getContext()));
        }

    };

    /**
     * CaptureRequest.Builder 用于摄像机预览请求配置
     */
    private CaptureRequest.Builder mPreviewRequestBuilder; // 预览请求配置
    private CaptureRequest mPreviewRequest; // 预览请求

    /**
     * 相机当前的拍照状态。
     */
    private int mState = STATE_PREVIEW;

    /**
     *  Semaphore 可防止应用程序在关闭相机前退出。
     */
    private final Semaphore mCameraOpenCloseLock = new Semaphore(1);

    /**
     * 当前的相机设备是否支持Flash（闪光灯）
     */
    private boolean mFlashSupported;

    /**
     * 相机传感器的方向
     */
    private int mSensorOrientation;

    /**
     * CameraCaptureSession.CaptureCallback 处理与JPEG捕获有关的事件。
     */
    private final CameraCaptureSession.CaptureCallback mCaptureCallback
            = new CameraCaptureSession.CaptureCallback() {

        private void process(CaptureResult result) {
            switch (mState) { // 判断当前的拍照状态
                case STATE_PREVIEW: {
                    // 相机预览正常工作时，我们无需执行任何操作。
                    break;
                }
                /**
                 * 调用拍照方法后，会进入STATE_WAITING_LOCK状态，此时获取Integer afState = result.get(CaptureResult.CONTROL_AF_STATE)
                 * 的对焦状态afState 在某些机器上面，连续拍了几张图片之后，afState 会一直处于CaptureResult.CONTROL_AF_STATE_PASSIVE_SCAN状态，
                 * 表示一个持续聚焦的算法正在做扫描。镜头正在移动中。然而实际上你并没有移动镜头。这里会导致后续的对焦完成ImageReader取出对焦完成的图像数据无法进行。
                 * 也就是无法再拍照了。
                 */
                case STATE_WAITING_LOCK: { //等待相机焦点被锁定 调用拍照方法后 会进入到STATE_WAITING_LOCK状态
                    Integer afState = result.get(CaptureResult.CONTROL_AF_STATE); // 自动聚焦状态afState
                    if (afState == null) {
                        captureStillPicture();
                        /**
                         * afState 的状态为1，即CONTROL_AF_STATE_PASSIVE_SCAN。 持续聚焦的算法正在做扫描
                         * 无法再继续走到后续的CONTROL_AF_STATE_FOCUSED_LOCKED 和 CONTROL_AF_STATE_NOT_FOCUSED_LOCKED 状态，
                         * 导致无法取出图像数据，进而完成拍照功能。
                         */
                    } else if (CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED == afState ||
                            CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED == afState) {
                        // CONTROL_AE_STATE在某些设备上可以为空
                        // 相机预览正常工作时，我们无需执行任何操作。
                        Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE); // 自动曝光状态
                        if (aeState == null ||
                                aeState == CaptureResult.CONTROL_AE_STATE_CONVERGED) {
                            // 已拍摄照片
                            mState = STATE_PICTURE_TAKEN;
                            captureStillPicture();
                        } else {
                            runPrecaptureSequence();
                        }
                    }
                    break;
                }
                /**
                 * 等待曝光为预拍摄状态。
                 */
                case STATE_WAITING_PRECAPTURE: {
                    // CONTROL_AE_STATE在某些设备上可以为null
                    Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
                    if (aeState == null ||
                            aeState == CaptureResult.CONTROL_AE_STATE_PRECAPTURE ||
                            aeState == CaptureRequest.CONTROL_AE_STATE_FLASH_REQUIRED) {
                        // 拍照状态为 ======== 曝光状态为预拍摄以外的状态
                        mState = STATE_WAITING_NON_PRECAPTURE;
                    }
                    break;
                }
                /**
                 * 曝光状态为预拍摄以外的状态
                 */
                case STATE_WAITING_NON_PRECAPTURE: {
                    // CONTROL_AE_STATE在某些设备上可以为null
                    Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
                    if (aeState == null || aeState != CaptureResult.CONTROL_AE_STATE_PRECAPTURE) {
                        // 已拍摄照片
                        mState = STATE_PICTURE_TAKEN;
                        captureStillPicture();
                    }
                    break;
                }
            }
        }

        @Override
        public void onCaptureProgressed(@NonNull CameraCaptureSession session,
                                        @NonNull CaptureRequest request,
                                        @NonNull CaptureResult partialResult) {
            process(partialResult);
        }

        @Override
        public void onCaptureCompleted(@NonNull CameraCaptureSession session,
                                       @NonNull CaptureRequest request,
                                       @NonNull TotalCaptureResult result) {
            // 在预览的回调函数中处理人脸检测
            onCameraImagePreviewed(result);

            process(result);
        }

    };

    /**
     * 在UI线程上显示Toast
     *
     * @param text The message to show 显示的讯息
     */
    private void showToast(final String text) {
        final Activity activity = getActivity();
        if (activity != null) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(activity, text, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    /**
     * 给定相机支持的{@code Size}个{@code choices}，请选择最小的一个，该大小至少与相应的纹理视图大小一样大，
     * 并且最大与相应的最大视图大小一样大，并且宽高比与指定值匹配。如果不存在这种尺寸，请选择最大尺寸，最大尺
     * 寸与相应的最大尺寸一样大，并且其宽高比与指定值匹配。
     *
     * @param choices           相机支持的预期输出类别的尺寸列表
     * @param textureViewWidth  纹理视图相对于传感器坐标的宽度
     * @param textureViewHeight 纹理视图相对于传感器坐标的高度
     * @param maxWidth          可以选择的最大宽度
     * @param maxHeight         可以选择的最大高度
     * @param aspectRatio       宽高比
     *                          最佳{@code Size}，如果没有足够大的值，则为任意值
     */
    private static Size chooseOptimalSize(Size[] choices, int textureViewWidth,
                                          int textureViewHeight, int maxWidth, int maxHeight, Size aspectRatio) {

        // 收集至少与预览Surface一样大的受支持的分辨率
        List<Size> bigEnough = new ArrayList<>();
        // 收集小于预览Surface的支持的分辨率
        List<Size> notBigEnough = new ArrayList<>();
        int w = aspectRatio.getWidth();
        int h = aspectRatio.getHeight();
        for (Size option : choices) {
            if (option.getWidth() <= maxWidth && option.getHeight() <= maxHeight &&
                    option.getHeight() == option.getWidth() * h / w) {
                if (option.getWidth() >= textureViewWidth &&
                        option.getHeight() >= textureViewHeight) {
                    bigEnough.add(option);
                } else {
                    notBigEnough.add(option);
                }
            }
        }

        // 选择足够大的那些中的最小者。如果没有足够大的Size，则从不够大的Size中选最大的一个。
        if (bigEnough.size() > 0) {
            return Collections.min(bigEnough, new CompareSizesByArea());
        } else if (notBigEnough.size() > 0) {
            return Collections.max(notBigEnough, new CompareSizesByArea());
        } else {
            // 找不到合适的预览尺寸
            Log.e(TAG, "找不到合适的预览尺寸");
            return choices[0];
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.camera_fragment_layout, container, false);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onViewCreated(final View view, Bundle savedInstanceState) {

        sharedPreferences = getActivity().getSharedPreferences("com.example.cameraapp_preferences", Context.MODE_PRIVATE);
        view.findViewById(R.id.picture).setOnClickListener(this);
        view.findViewById(R.id.info).setOnClickListener(this);

        view.findViewById(R.id.picture_iv).setOnClickListener(this); // 显示拍照之后的图片
        view.findViewById(R.id.pictures).setOnClickListener(this); // 拍照
        view.findViewById(R.id.videotapes).setOnClickListener(this); // 录像
        view.findViewById(R.id.slowMotion).setOnClickListener(this); // 慢动作
        view.findViewById(R.id.change).setOnClickListener(this); // 摄像头切换
        view.findViewById(R.id.delayed).setOnClickListener(this); //延时
        view.findViewById(R.id.continuous).setOnClickListener(this);// 连拍
        view.findViewById(R.id.setting).setOnClickListener(this); // 设置
        view.findViewById(R.id.flash).setOnClickListener(this); // 闪光灯

        tv_timer = view.findViewById(R.id.timer); // 拍照倒计时

        textView1 = view.findViewById(R.id.textView1);
        faceView = view.findViewById(R.id.faceView);
        //隐藏背景色，以免标注人脸时挡住预览画面
        faceView.setAlpha(0.9f);

        mDelay= view.findViewById(R.id.delay);
        Delay_time= view.findViewById(R.id.delay_time); // 延长时间拍照

        mTextureView = (AutoFitTextureView)view.findViewById(R.id.texture); // 自定义控件
        mPicture_tv = (ImageView) view.findViewById(R.id.picture_iv); // 显示拍照之后的图片
        iv_pictures = (ImageView) view.findViewById(R.id.picture); // 拍照按钮
        iv_info = (ImageView) view.findViewById(R.id.info); // 显示信息
        iv_flash = (ImageView) view.findViewById(R.id.flash);//闪光灯
        iv_setting = (ImageView) view.findViewById(R.id.setting);// 设置
        iv_change = (ImageView) view.findViewById(R.id.change);// 摄像头切换
        tv_videotapes = (TextView) view.findViewById(R.id.videotapes);// 录像
        tv_delayed = (TextView) view.findViewById(R.id.delayed);// 延时
        tv_pictures = (TextView) view.findViewById(R.id.pictures);//拍照
        tv_continuous = (TextView) view.findViewById(R.id.continuous);//连拍
        tv_slowMotion = (TextView) view.findViewById(R.id.slowMotion);// 慢动作
        textView = (TextView)view.findViewById(R.id.textView);// 水印
        time = (Chronometer)view.findViewById(R.id.time);// 计时器
        time.setVisibility(View.GONE);
        textView.setVisibility(View.GONE);
        /**
         * 如果手机记录的最新一张图片被删除，ImageUtils.getLatestThumbBitmap（）返回值为空。
         */
        if(ImageUtils.getLatestThumbBitmap(getContext()) != null){
            mPicture_tv.setImageBitmap(ImageUtils.getLatestThumbBitmap(getContext()));
        }else{
            mPicture_tv.setImageDrawable(ContextCompat.getDrawable(getActivity(),R.mipmap.shutter_panorama));
        }

        ImageUtils.mDatas = ImageUtils.getThumbBitmapIndexs(getContext());
        ImageUtils.mContext = getContext();
    }

    @Override
    public void onActivityCreated(android.os.Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
//        mFile = new File(getActivity().getExternalFilesDir(null), "pic.jpg");
//        mFile = MediaFunc.getOutputMediaFile(MediaFunc.MEDIA_TYPE_IMAGE, "CAMERA");
        setmFile();
    }

    public void setmFile() {
        this.mFile = MediaFunc.getOutputMediaFile(MediaFunc.MEDIA_TYPE_IMAGE, "CAMERA");;
    }

    public void setmFile(File mFile) {
        this.mFile = mFile;
    }

    /**
     * Activity的声明周期之一  在onResume()进行刷新操作  按照Activity的生命周期的模型 当activity恢复的时候  onResume()这个方法是会被调用的
     * 因此这是一个刷新的好机会
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onResume() {
        super.onResume();
        startBackgroundThread();

        // 当屏幕关闭并重新打开时，SurfaceTexture已经可用，并且不会调用“ onSurfaceTextureAvailable”。
        // 在这种情况下，我们可以打开相机并从此处开始预览（否则，我们等到SurfaceTextureListener中的曲面
        // 准备好为止）。
        if (mTextureView.isAvailable()) {
            openCamera(mTextureView.getWidth(), mTextureView.getHeight());
        } else {
            mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
        }
    }

    /**
     *  Activity 的五大生命周期  onCreate() onStart() onResume() onPause() onStop()
     *
     *  程序在启动的时候调用 ------ onCreate() onStart() onResume()
     *  锁执行的时候调用--------- onPause() onStop()
     *  进入后台快捷键执行的生命周期是 --------- onPause() onStop()
     */
    @Override
    public void onPause() {
        closeCamera();
        stopBackgroundThread(); // 停止后台线程及其子线程
        super.onPause();
    }

    /**
     *  权限问题  权限的检查判断  如果应用具有此权限 方法将返回PackageManager.PERMISSION_GRANTED 并且应用可以继续操作
     *           如果应用不具有此权限 方法将返回FRAGMENT_DIALOG 且应用必须明确向应用用户要求权限
     * @param requestCode 请求码
     * @param permissions 认证
     * @param grantResults 全新分类处理
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults.length != 1 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                new PermissionDialog().show(getChildFragmentManager(), FRAGMENT_DIALOG);
//                    ErrorDialog.newInstance(getString(R.string.request_permission))
//                            .show(getChildFragmentManager(), FRAGMENT_DIALOG);
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    /**
     * 获取支持的最高人脸检测级别
     *
     * @return
     */

    private int getFaceDetectMode() {

        if (faceDetectModes == null) {
            return CaptureRequest.STATISTICS_FACE_DETECT_MODE_FULL;
        } else {
            return faceDetectModes[faceDetectModes.length - 1];
        }
    }


    private TextureView faceView;
    private TextView textView1;
    ;//用于标注人脸
    /**
     * 人脸检测相关属性
     */
    // Rect rRect;//相机成像矩形
    Size cPixelSize;//相机成像尺寸
    private int[] faceDetectModes;
    Paint pb;// 画笔

    /**
     * 处理相机画面处理完成事件，获取检测到的人脸坐标，换算并绘制方框
     *
     *
     *
     *
     * @param result
     */
    private void onCameraImagePreviewed(CaptureResult result) {
        Face faces[] = result.get(CaptureResult.STATISTICS_FACES);
        showMessage(false, "人脸个数:[" + faces.length + "]");

        Canvas canvas = faceView.lockCanvas();
        canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
        if (faces.length > 0) {
            for (int i = 0; i < faces.length; i++) {
                Rect fRect = faces[i].getBounds();
                Log.i(TAG,
                        " Rect " + fRect.left + "," + fRect.top + "," + fRect.right + "," + fRect.bottom);
                float scaleWidth = canvas.getHeight() * 1.0f / cPixelSize.getWidth();
                float scaleHeight = canvas.getWidth() * 1.0f / cPixelSize.getHeight();
                Log.e(TAG, " Scale " + scaleWidth + "," + scaleHeight);
                int l = (int) (fRect.left * scaleWidth);
                int t = (int) (fRect.top * scaleHeight);
                int r = (int) (fRect.right * scaleWidth);
                int b = (int) (fRect.bottom * scaleHeight);
                if (mCameraState == 1) {
                    Log.d(TAG, " 前置 " + l + "," + t + "," + r + "," + b);
                    canvas.drawRect(canvas.getWidth() - b, canvas.getHeight() - r,
                            canvas.getWidth() - t, canvas.getHeight() - l, getPaint());
                } else if (mCameraState== 0) {
                    Log.d(TAG, " 后置 " + l + "," + t + "," + r + "," + b);
                    canvas.drawRect(canvas.getWidth() - b, l, canvas.getWidth() - t, r, getPaint());
                }
            }
        }
        faceView.unlockCanvasAndPost(canvas);
    }

    /**
     * 初始化画笔
     */
    private Paint getPaint() {
        if (pb == null) {
            pb = new Paint();
            pb.setColor(Color.RED);
            pb.setStrokeWidth(15);
            pb.setStyle(Paint.Style.STROKE);//使绘制的矩形中空
        }
        return pb;
    }

    private static void Log(String message) {
        Log.i(CameraFragment.class.getName(), message);
    }






    /**
     * 设置与摄像机相关的成员变量。
     *
     * @param width  相机预览可用尺寸的宽度
     * @param height 相机预览可用尺寸的高度
     */
    @SuppressWarnings("SuspiciousNameCombination")
    private void setUpCameraOutputs(int width, int height) {
        Activity activity = getActivity();
        // 获取所有手机上支持的摄像头管理者
        CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
        sharedPreferences=getActivity().getSharedPreferences("com.martinwj.camera2demo_preferences.xml",0);
        SharedPreferences.Editor editor=getActivity().getSharedPreferences("com.martinwj.camera2demo_preferences.xml",0).edit();
        editor.putString("setting_awb","7");

        try {
            // 获取可用的摄像头列表遍历
            for (String cameraId : manager.getCameraIdList()) {
                CameraCharacteristics characteristics // 获取摄像头的特征信息
                        = manager.getCameraCharacteristics(cameraId);

                //可用于判断是否支持人脸检测，以及支持到哪种程度
                faceDetectModes = characteristics.get(CameraCharacteristics.STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES);//获取支持的人脸检测模式
//                cameraRect= characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);//成像区域
                Rect cRect = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);//获取成像区域
                cPixelSize = characteristics.get(CameraCharacteristics.SENSOR_INFO_PIXEL_ARRAY_SIZE);//获取成像尺寸，同上

                int [] AWB=characteristics.get(CameraCharacteristics.CONTROL_AWB_AVAILABLE_MODES);//获取到当前相机可用的AWB模式
                for (int awb:AWB) {
                    Log.e(TAG,String.valueOf(awb));
                }

                // 在此示例中，我们不使用前置摄像头。
                Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
                if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
                    continue;
                }
                // 获取管理摄像头支持的所有输出格式和尺寸
                StreamConfigurationMap map = characteristics.get(
                        CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                if (map == null) {
                    continue;
                }
                sizeArr = map.getOutputSizes(ImageFormat.JPEG);
                // 对于静态图像捕获，我们使用最大的可用尺寸。1920*1080
//                Size largest = Collections.max(Arrays.asList(sizeArr), new CompareSizesByArea());
                Size largest = new Size(1920, 1080);

                // 修改图片分辨率  用surface最大size初始化ImageReader
                //largest.getWidth(), largest.getHeight(), 1*1 2992*2992   4*3 1920*1440   16*9 1920*1080
                if(mRatio == 0){ // 原始分辨率
                    mImageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(), ImageFormat.JPEG, /*maxImages*/2);
                }else if(mRatio == 1){  //分辨率1456x1456
                    mImageReader = ImageReader.newInstance(2992, 2992, ImageFormat.JPEG, /*maxImages*/2);
                }else if(mRatio == 2){ //分辨率480x640
                    mImageReader = ImageReader.newInstance(1920, 1440, ImageFormat.JPEG, /*maxImages*/2);
                }else {
                    mImageReader = ImageReader.newInstance(1920, 1080, ImageFormat.JPEG, /*maxImages*/2);
                }
                // mOnImageAvailableListener ----- 准备好保存静止图像 mBackgroundHandler ----- 后台运行任务
                mImageReader.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler);

                // 找出我们是否需要交换尺寸以获得相对于传感器坐标的预览尺寸，获取屏幕旋转的方向
                int displayRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
                // 恒定条件下不检查 mSensorOrientation --- 相机传感器的方向
                mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
                // 判断屏幕旋转的方向
                boolean swappedDimensions = false;
                switch (displayRotation) {
                    case Surface.ROTATION_0:
                    case Surface.ROTATION_180:
                        if (mSensorOrientation == 90 || mSensorOrientation == 270) {
                            swappedDimensions = true;
                        }
                        break;
                    case Surface.ROTATION_90:
                    case Surface.ROTATION_270:
                        if (mSensorOrientation == 0 || mSensorOrientation == 180) {
                            swappedDimensions = true;
                        }
                        break;
                    default:
                        // 显示旋转无效：
                        Log.e(TAG, "无效的旋转显示：" + displayRotation);
                }
                /**
                 * 获取屏幕的尺寸大小比例
                 */
                Point displaySize = new Point();
                activity.getWindowManager().getDefaultDisplay().getSize(displaySize);
                int rotatedPreviewWidth = width;
                int rotatedPreviewHeight = height;
                int maxPreviewWidth = displaySize.x; // 得到屏幕的宽度
                int maxPreviewHeight = displaySize.y;// 得到屏幕的高度

                if (swappedDimensions) {
                    rotatedPreviewWidth = height;
                    rotatedPreviewHeight = width;
                    maxPreviewWidth = displaySize.y;
                    maxPreviewHeight = displaySize.x;
                }

                if (maxPreviewWidth > MAX_PREVIEW_WIDTH) {
                    maxPreviewWidth = MAX_PREVIEW_WIDTH;
                }

                if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) {
                    maxPreviewHeight = MAX_PREVIEW_HEIGHT;
                }

                Size[] sizes = map.getOutputSizes(SurfaceTexture.class);
                for (Size size : sizes) {
                    System.out.println(size);
                }

                //修改预览分辨率
                if(mRatio == 0){
                    // 选择最优的预览Size
                    mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth, maxPreviewHeight, largest);
//                    mPreviewSize = new Size(rotatedPreviewWidth,rotatedPreviewHeight);//全屏预览
                }else if(mRatio == 1){
                    mPreviewSize = new Size(1456,1456);
                }else if(mRatio == 2){
                    mPreviewSize = new Size(640,480);
                }else {
                    mPreviewSize = new Size(1280,720);
                }
                // 危险！尝试使用太大的预览大小可能会超出相机总线的带宽限制，从而产生漂亮的预览，但会存储垃圾回收数据。
//                mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
//                        rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
//                        maxPreviewHeight, largest);

                // 我们将TextureView的长宽比调整为我们选择的预览大小。
                int orientation = getResources().getConfiguration().orientation;
                if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    mTextureView.setAspectRatio(
                            mPreviewSize.getWidth(), mPreviewSize.getHeight());
                } else {
                    mTextureView.setAspectRatio(
                            mPreviewSize.getHeight(), mPreviewSize.getWidth());
                }

                // 检查是否支持闪光灯。
                Boolean available = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
                mFlashSupported = available == null ? false : available;

                mCameraId = cameraId;
                return;
            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            // 当前，当使用Camera2API但运行此代码的设备不支持NPE时，将引发NPE。
            ErrorDialog.newInstance(getString(R.string.camera_error))
                    .show(getChildFragmentManager(), FRAGMENT_DIALOG);
        }
    }

    /**
     * 打开由{@link CameraFragment#mCameraId}指定的摄像机。
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void openCamera(int width, int height) {
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            requestCameraPermission();
            return;
        }
        setUpCameraOutputs(width, height);
        configureTransform(width, height);
        Activity activity = getActivity();
        CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
        try {
            if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
                // 等待锁定相机打开超时。
                throw new RuntimeException("等待打开锁定相机.");
            }
            mCameraId = String.valueOf(mCameraState);
            manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            // 尝试锁定相机打开时中断。
            throw new RuntimeException("尝试中断打开锁定相机.", e);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void requestCameraPermission() {
        if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
            new PermissionDialog().show(getFragmentManager(), "PermissionDeny");
        } else {
            requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
        }
    }

    /**
     * 关闭当前的{@link CameraDevice}。
     */
    private void closeCamera() {
        try {
            mCameraOpenCloseLock.acquire();
            if (null != mCaptureSession) {
                mCaptureSession.close();
                mCaptureSession = null;
            }
            if (null != mCameraDevice) {
                mCameraDevice.close();
                mCameraDevice = null;
            }
            if (null != mImageReader) {
                mImageReader.close();
                mImageReader = null;
            }
        } catch (InterruptedException e) {
            throw new RuntimeException("尝试中断关闭锁定相机.", e);
        } finally {
            mCameraOpenCloseLock.release();
        }
    }

    /**
     * 启动后台线程及其{@link Handler}。
     */
    private void startBackgroundThread() {
        mBackgroundThread = new HandlerThread("CameraBackground");
        mBackgroundThread.start();
        mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
    }

    /**
     * 停止后台线程及其{@link Handler}。
     */
    private void stopBackgroundThread() {
        mBackgroundThread.quitSafely();
        try {
            mBackgroundThread.join();
            mBackgroundThread = null;
            mBackgroundHandler = null;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建一个新的{@link CameraCaptureSession}用于摄像头预览。
     */
    private void createCameraPreviewSession() {
        try {
            // 根据SurfaceTexture配置Surface 、用于显示预览画面
            SurfaceTexture texture = mTextureView.getSurfaceTexture();
            assert texture != null;

            // 我们将默认缓冲区的大小配置为所需的摄像机预览的大小。
            texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());

            // 这是我们需要开始预览的输出Surface。
            Surface surface = new Surface(texture);

            // 我们使用输出Surface设置一个CaptureRequest.Builder，创建一个预览请求配置类 并添加surface
            mPreviewRequestBuilder
                    = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            mPreviewRequestBuilder.addTarget(surface);

            // 在这里，我们创建了CameraCaptureSession来进行摄像机预览。 使用surface来创建session;
            mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
                    // 获取数据会话的状态接口回调类 我们创建相机预览图像/拍照/录像都需要这个回调类。
                    // 来告诉我们获取数据会话的通道状态是配置成功还是配置失败
                    new CameraCaptureSession.StateCallback() {

                        @Override
                        public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                            // 相机已经关闭
                            if (null == mCameraDevice) {
                                return;
                            }

                            // 会话准备就绪后，我们开始显示预览。
                            mCaptureSession = cameraCaptureSession;
                            try {
                                //设置人脸检测级
                                mPreviewRequestBuilder.set(CaptureRequest.STATISTICS_FACE_DETECT_MODE, getFaceDetectMode());
                                // 自动对焦应连续进行相机预览。
                                mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                                        CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
                                // 必要时会自动启用闪光灯。
                                setAutoFlash(mPreviewRequestBuilder);
                                // AWB设置  预览时候也要将AWB添加到mPreviewRequestBuilder中
                                setAWBMode(mPreviewRequestBuilder);

                                // 最后，创建预览的request、通过setRepeatingRequest将预览请求提就开始预览
                                mPreviewRequest = mPreviewRequestBuilder.build();
                                mCaptureSession.setRepeatingRequest(mPreviewRequest,
                                        mCaptureCallback, mBackgroundHandler);
                            } catch (CameraAccessException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onConfigureFailed(
                                @NonNull CameraCaptureSession cameraCaptureSession) {
                            showToast("Failed");
                        }
                    }, null
            );
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置白平衡状态
     */
    private SharedPreferences sharedPreferences;

    private void setAWBMode(CaptureRequest.Builder mRequestBuilder) {

        String awbMode = sharedPreferences.getString("setting_awb", "0");
        Log.i(TAG, "setAWBMode: "+awbMode);
        switch (awbMode) {
           /* case "0":
                mRequestBuilder.set(CaptureRequest.CONTROL_AWB_MODE, CaptureRequest.CONTROL_AWB_MODE_OFF);
                break;*/
            case "1":
                mRequestBuilder.set(CaptureRequest.CONTROL_AWB_MODE, CaptureRequest.CONTROL_AWB_MODE_AUTO);
                break;
            case "2":
                mRequestBuilder.set(CaptureRequest.CONTROL_AWB_MODE, CaptureRequest.CONTROL_AWB_MODE_INCANDESCENT);
                break;
            case "3":
                mRequestBuilder.set(CaptureRequest.CONTROL_AWB_MODE, CaptureRequest.CONTROL_AWB_MODE_FLUORESCENT);
                break;
            case "4":
                mRequestBuilder.set(CaptureRequest.CONTROL_AWB_MODE, CaptureRequest.CONTROL_AWB_MODE_WARM_FLUORESCENT);
                break;
            case "5":
                mRequestBuilder.set(CaptureRequest.CONTROL_AWB_MODE, CaptureRequest.CONTROL_AWB_MODE_DAYLIGHT);
                break;
            case "6":
                Log.i(TAG, "setAWBMode: 6 run");
                mRequestBuilder.set(CaptureRequest.CONTROL_AWB_MODE, CaptureRequest.CONTROL_AWB_MODE_CLOUDY_DAYLIGHT);
                break;
            case "7":
                mRequestBuilder.set(CaptureRequest.CONTROL_AWB_MODE, CaptureRequest.CONTROL_AWB_MODE_TWILIGHT);
                break;
            case "8":
                mRequestBuilder.set(CaptureRequest.CONTROL_AWB_MODE, CaptureRequest.CONTROL_AWB_MODE_SHADE);
                break;

        }
    }

    /**
     * 将必要的{@link android.graphics.Matrix}转换配置为“mTextureView”。在setUpCameraOutputs中确定
     * 了摄像机预览大小并且固定了mTextureView大小之后，应调用此方法。
     *
     * @param viewWidth  `mTextureView`的宽度
     * @param viewHeight `mTextureView`的高度
     */
    private void configureTransform(int viewWidth, int viewHeight) {
        Activity activity = getActivity();
        if (null == mTextureView || null == mPreviewSize || null == activity) {
            return;
        }
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        Matrix matrix = new Matrix();
        RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
        RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
        float centerX = viewRect.centerX();
        float centerY = viewRect.centerY();
        if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
            bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
            matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
            float scale = Math.max(
                    (float) viewHeight / mPreviewSize.getHeight(),
                    (float) viewWidth / mPreviewSize.getWidth());
            matrix.postScale(scale, scale, centerX, centerY);
            matrix.postRotate(90 * (rotation - 2), centerX, centerY);
        } else if (Surface.ROTATION_180 == rotation) {
            matrix.postRotate(180, centerX, centerY);
        }
        mTextureView.setTransform(matrix);
    }

    /**
     * 启动捕获图像。
     */
    private void takePicture() {
        Log.e("1111","2222");
        lockFocus();
    }

    /**
     * 锁定焦点是静止图像拍摄的第一步。
     */
    private void lockFocus() {
        try {
            if(mFlash == 1) {
                //开启闪光灯
                mPreviewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
            }else {
                mPreviewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
            }
            // 这是告诉相机锁定焦点的方法。
            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_START);
            // 告诉mCaptureCallback等待锁。
            mState = STATE_WAITING_LOCK;
            mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
                    mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 运行预捕获序列以捕获静止图像。当我们从{@link #lockFocus()}在{@link #mCaptureCallback}中收到响
     * 应时，应调用此方法。
     */
    private void runPrecaptureSequence() {
        try {
            // 这是告诉相机触发的方法。
            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
                    CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_START);
            // 告诉mCaptureCallback等待设置预捕获序列。
            mState = STATE_WAITING_PRECAPTURE;
            mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
                    mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 拍摄静止图像。当我们在{@link #lockFocus()}的{@link #mCaptureCallback}中收到响应时，应调用此方法。
     */
    private void captureStillPicture() {
        try {
            final Activity activity = getActivity();
            if (null == activity || null == mCameraDevice) {
                return;
            }
            // 这是我们用来拍照的CaptureRequest.Builder。 添加surface的拍摄图片的输出
            final CaptureRequest.Builder captureBuilder =
                    mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
            // 将 ImageReader 的surface设为目标
            captureBuilder.addTarget(mImageReader.getSurface());

            // 使用与预览相同的AE和AF模式。 设置自动对焦模式
            captureBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                    CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);

            setAutoFlash(captureBuilder); // 闪光灯设置
            // 白平衡设置
            setAWBMode(captureBuilder);
            // 获取手机屏幕的方向
            int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
//            if(mCameraState == 1) {
//
//            }
            // 根据设备的方向计算设置照片的方向
            captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, getOrientation(rotation));
            // 获取数据会话的数据接口回调类 主要负责回调获取数据的声明周期 比如开始/进行中/完成/失败等工作，
            // 如果你并不需要对声明周期做操作 所以有时也没用，但是也是必须创建的一个回调接口类 是在创建预览图像/拍照/录像的时候添加进去
            CameraCaptureSession.CaptureCallback CaptureCallback
                    = new CameraCaptureSession.CaptureCallback() {
                @Override
                public void onCaptureCompleted(@NonNull CameraCaptureSession session,
                                               @NonNull CaptureRequest request,
                                               @NonNull TotalCaptureResult result) {
                    showToast("Saved: " + mFile);
                    Log.d(TAG, mFile.toString());
                    unlockFocus();
                }
            };
            // 停止连续取景
            mCaptureSession.stopRepeating();
            mCaptureSession.abortCaptures();
            // 设置拍照监听  captureBuilder.build() 拍照
            mCaptureSession.capture(captureBuilder.build(), CaptureCallback, null);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 从指定的屏幕旋转角度检索JPEG方向。
     *
     * @param rotation 屏幕旋转。
     * @return JPEG方向（0、90、270和360中的一个）
     */
    private int getOrientation(int rotation) {
        // 对于大多数设备，传感器方向为90，对于某些设备（例如Nexus 5X），传感器方向为270。我们必须
        // 考虑到这一点，并正确旋转JPEG。对于方向为90的设备，我们只需从ORIENTATIONS返回映射即可。
        // 对于方向为270的设备，我们需要将JPEG旋转180度。
        return (ORIENTATIONS.get(rotation) + mSensorOrientation + 270) % 360;
    }

    /**
     * 释放焦点。静止图像捕获序列完成后应调用此方法。
     */
    private void unlockFocus() {
        try {
            // 重置自动对焦触发器
            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
                    CameraMetadata.CONTROL_AF_TRIGGER_CANCEL);
            setAutoFlash(mPreviewRequestBuilder);
            mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
                    mBackgroundHandler);
            // 此后，相机将返回到预览的正常状态。
            mState = STATE_PREVIEW;
            mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback,
                    mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    // 快门声音
    private MediaPlayer mediaPlayer;
    private AudioManager audioManager;

    /**
     * 拍照时发出声音
     */
    @SuppressLint("ServiceCast")
    private void captureVoice(){
        audioManager  = (AudioManager)getSystemService(Service.ACCOUNT_SERVICE);
        mediaPlayer = MediaPlayer.create(getActivity().getApplicationContext(),R.raw.voice);
        mediaPlayer.start();
    }

    private Object getSystemService(String accountService) {
        return null;
    }

    /**
     * 延时拍照
     */
    private boolean delayState= true;
    private int delayTime=0;//延时时间
    private CountDownTimer countDownTimer;
    private boolean flag = true;

    private EditText mDelay;
    private TextView Delay_time;

    /**
     * 延长时间拍照定时器
     * @param countDownTimer
     */
    private void setCountDownTimer(CountDownTimer countDownTimer) {
        this.countDownTimer =new CountDownTimer(delayTime,1000){

            @Override
            public void onTick(long millisUntilFinished) {
                Delay_time.setVisibility(View.VISIBLE);
                Delay_time.setText("" +((millisUntilFinished / 1000)+1));
                tv_timer.setText(millisUntilFinished / 1000 + 1 + "");
            }

            @SuppressLint("NewApi")
            @Override
            public void onFinish() {
                tv_timer.setVisibility(View.GONE);
                Delay_time.setVisibility(View.GONE);
                takePicture();
                Toast.makeText(getContext(),"已保存到相册",Toast.LENGTH_SHORT).show();
            }
        };
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @SuppressLint({"NonConstantResourceId", "ResourceType", "NewApi"})
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.picture: {  // 拍照
                captureVoice();// 拍照发出声音
                if (mRecordingVideo == 3) {
                    captureVoice();// 拍照发出声音
                    if (flag){
                        if (mDelay.getText().toString()!=null && !mDelay.getText().toString().equals("")){
                            delayState = false;
                        }
                        if (delayState){
                            takePicture();
                        }else {
                            tv_timer.setVisibility(View.VISIBLE);// 延长时间拍照可见
                            delayTime=Integer.parseInt(mDelay.getText().toString().trim())*1000;
                            SharedPreferences.Editor editor =getActivity().getSharedPreferences("DELAY_TIME",0).edit();
                            editor.putString("info_content", Delay_time.getText().toString());
                            editor.commit();
                            setCountDownTimer(countDownTimer);
                            System.out.println("点击拍照之后的delayTime"+delayTime);
                            countDownTimer.start();
                            flag = false;
                        }
                    }else {
                        countDownTimer.cancel();
                        Delay_time.setVisibility(View.GONE);
                        takePicture();
                    }
                } else if (mRecordingVideo == 1) {
                    Toast.makeText(getActivity(),"开始录像", Toast.LENGTH_SHORT).show();
                    // 设置开始计时时间
                    captureVoice();// 录像时发出声音
                    time.setVisibility(View.VISIBLE);
                    time.setBase(SystemClock.elapsedRealtime());
                    time.setFormat("录制时间： %s");
                    //启动计时器
                    time.start();
                    mMediaRecorder = new MediaRecorder();
                    startRecordingVideo();
                    // 隐藏按钮
                    tv_timer.setVisibility(View.GONE);
                    iv_info.setVisibility(View.GONE);
                    iv_flash.setVisibility(View.GONE);
                    iv_setting.setVisibility(View.GONE);
                    iv_change.setVisibility(View.GONE);
                    mPicture_tv.setVisibility(View.GONE);
                    tv_slowMotion.setVisibility(View.GONE);
                    tv_delayed.setVisibility(View.GONE);
                    tv_pictures.setVisibility(View.GONE);
                    tv_videotapes.setVisibility(View.GONE);
                    tv_continuous.setVisibility(View.GONE);
                    mDelay.setVisibility(View.GONE);
                } else if (mRecordingVideo == 2) {
                    Toast.makeText(getActivity(),"停止录像", Toast.LENGTH_SHORT).show();
                    // 停止计时
                    captureVoice();// 停止录像时候发出声音
                    time.setVisibility(View.GONE);
                    time.stop();
                    stopRecordingVideo();
                    iv_pictures.setImageDrawable(ContextCompat.getDrawable(getActivity(),R.mipmap.video_capture));
                    // 显示按钮
                    tv_timer.setVisibility(View.VISIBLE);
                    iv_info.setVisibility(View.VISIBLE);
                    iv_flash.setVisibility(View.VISIBLE);
                    iv_setting.setVisibility(View.VISIBLE);
                    iv_change.setVisibility(View.VISIBLE);
                    mPicture_tv.setVisibility(View.VISIBLE);
                    tv_slowMotion.setVisibility(View.VISIBLE);
                    tv_delayed.setVisibility(View.VISIBLE);
                    tv_pictures.setVisibility(View.VISIBLE);
                    tv_videotapes.setVisibility(View.VISIBLE);
                    tv_continuous.setVisibility(View.VISIBLE);
                    mDelay.setVisibility(View.VISIBLE);
                }else if(mRecordingVideo == 4){
                    for(int i = 1; i < 3; i++){
                        captureStillPicture();
                    }
                }
                break;
            }
            case R.id.pictures: { // 拍照
                mRecordingVideo = 3;
                iv_pictures.setImageDrawable(ContextCompat.getDrawable(getActivity(),R.drawable.yx_btn));
                setmFile();
                ImageUtils.mDatas = ImageUtils.getThumbBitmapIndexs(getContext());
                break;
            }
            case R.id.picture_iv: { // 打开相册
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivity(intent);
                /*Intent intent = new Intent(getActivity(), PictureActivity.class);*/
                startActivity(intent);
                break;
            }
            case R.id.change: { // 切换摄像头
                closeCamera();
                mCameraState = (mCameraState == 0) ? 1 : 0;
                //关闭闪光灯
                mFlash = 0;
                openCamera(mTextureView.getWidth(), mTextureView.getHeight());
                break;
            }
            case R.id.videotapes: { // 录像
                Toast.makeText(getActivity(),"录像", Toast.LENGTH_SHORT).show();
                iv_pictures.setImageDrawable(ContextCompat.getDrawable(getActivity(),R.mipmap.video_capture));
                mCaptureRate = 30;
                mRecordingVideo = 1;
                break;
            }
            case R.id.slowMotion: { //慢动作
                Toast.makeText(getActivity(),"慢动作", Toast.LENGTH_SHORT).show();
                iv_pictures.setImageDrawable(ContextCompat.getDrawable(getActivity(),R.mipmap.slowmotion));
                mRecordingVideo = 1;
                mCaptureRate = 120;
                break;
            }
            case R.id.delayed: {  //延时
                Toast.makeText(getActivity(),"延时", Toast.LENGTH_SHORT).show();
                iv_pictures.setImageDrawable(ContextCompat.getDrawable(getActivity(),R.mipmap.delayed));
                mRecordingVideo = 1;
                mCaptureRate = 15;
                break;
            }
            case R.id.continuous: { //连拍
                Toast.makeText(getActivity(),"连拍两张", Toast.LENGTH_SHORT).show();
                iv_pictures.setImageDrawable(ContextCompat.getDrawable(getActivity(),R.mipmap.continuous));
                mRecordingVideo = 4;
                break;
            }
            case R.id.flash: { //闪光灯
                if(mFlash == 0){
                    mFlash = 1;
                    Toast.makeText(getActivity(),"打开闪光灯", Toast.LENGTH_SHORT).show();
                }else{
                    mFlash = 0;
                    Toast.makeText(getActivity(),"关闭闪光灯", Toast.LENGTH_SHORT).show();
                }
                break;
            }
            case R.id.setting: {  //设置
               FragmentTransaction transaction = getFragmentManager().beginTransaction();
                transaction.replace(R.id.app_root, new SettingFragment(),
                        SettingFragment.class.getSimpleName());
                transaction.addToBackStack(SettingFragment.class.getSimpleName());
                transaction.commit();
                break;

//                PopupMenu popup = new PopupMenu(getActivity(), view);
//                popup.getMenuInflater().inflate(R.layout.menu_btn, popup.getMenu());
//                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
//                    @Override
//                    public boolean onMenuItemClick(MenuItem item) {
//                        switch (item.getItemId()) {
//                            case R.id.watermark:
//                                String message = "加水印";
//                                if (mWatermark == 1) {
//                                    textView.setVisibility(View.GONE);
//                                    message = "不加水印";
//                                } else {
//                                    textView.setVisibility(View.VISIBLE);
//                                }
//                                mWatermark = mWatermark == 0 ? 1 : 0;
//                                Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
//                                break;
//                            case R.id.ratio1:
//                                Toast.makeText(getActivity(), "w:1456 h:1456",
//                                        Toast.LENGTH_SHORT).show();
//                                closeCamera();
//                                mRatio = 1;
//                                onResume();
//                                break;
//                            case R.id.ratio2:
//                                Toast.makeText(getActivity(), "w:460 h:640",
//                                        Toast.LENGTH_SHORT).show();
//                                closeCamera();
//                                mRatio = 2;
//                                onResume();
//                                break;
//                            case R.id.ratio3:
//                                Toast.makeText(getActivity(), "w:720 h:1280",
//                                        Toast.LENGTH_SHORT).show();
//                                closeCamera();
//                                mRatio = 3;
//                                onResume();
//                                break;
//                        }
//                        return true;
//                    }
//                });
//                popup.show();
//                break;
            }
            case R.id.info: { // 详情
                Activity activity = getActivity();
                if (null != activity) {
                    new AlertDialog.Builder(activity)
                            .setMessage(R.string.intro_message)
                            .setPositiveButton(android.R.string.ok, null)
                            .show();
                }
                break;
            }

        }
    }

    /**
     * 自动开启闪光灯
     * @param requestBuilder
     */
    private void setAutoFlash(CaptureRequest.Builder requestBuilder) {
        switch (mFlash) {
            case 1:
                requestBuilder.set(CaptureRequest.FLASH_MODE,
                        CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH_REDEYE);
                break;
            case 2:
                requestBuilder.set(CaptureRequest.FLASH_MODE,
                        CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
                break;
        }

    }

    //录像调用函数
    private boolean hasPermissionsGranted(String[] permissions) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(getActivity(), permission)
                    != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void requestVideoPermissions() {
        if (shouldShowRequestPermissionRationale(Manifest.permission.RECORD_AUDIO)) {
            new PermissionDialog().show(getChildFragmentManager(), FRAGMENT_DIALOG);
        } else {
            requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, REQUEST_VIDEO_PERMISSIONS);
        }
    }

    private void setUpCaptureRequestBuilder(CaptureRequest.Builder builder) {
        builder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
    }

    private void updatePreview() {
        if (null == mCameraDevice) {
            return;
        }
        try {
            setUpCaptureRequestBuilder(mPreviewRequestBuilder);
            HandlerThread thread = new HandlerThread("CameraPreview");
            thread.start();
            mPreviewSession.setRepeatingRequest(mPreviewRequestBuilder.build(), null, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    private String getVideoFilePath(Context context) {
        final File dir = context.getExternalFilesDir(null);
        //获取外部存储文件对象
        return (dir == null ? "" : (dir.getAbsolutePath() + "/")) + System.currentTimeMillis() + ".mp4";
    }

    /**
     * 创建实例 MediaRecorder 设置相关参数setAudioSource
     * @throws IOException
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void setUpMediaRecorder() throws IOException {
        final Activity activity = getActivity();
        if (null == activity) {
            return;
        }
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
     /*   if (mNextVideoAbsolutePath == null || mNextVideoAbsolutePath.isEmpty()) {
            mNextVideoAbsolutePath = getVideoFilePath(getActivity());
        }*/
        File file = ImageUtils.insertVideoToDB(getActivity());
        mMediaRecorder.setOutputFile(file);
        mMediaRecorder.setVideoEncodingBitRate(10000000);
        mMediaRecorder.setCaptureRate(mCaptureRate);
        mMediaRecorder.setVideoFrameRate(30);
        mMediaRecorder.setVideoSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        switch (mSensorOrientation) {
            case SENSOR_ORIENTATION_DEFAULT_DEGREES:
                mMediaRecorder.setOrientationHint(ORIENTATIONS.get(rotation));
                break;
            case SENSOR_ORIENTATION_INVERSE_DEGREES:
                mMediaRecorder.setOrientationHint(INVERSE_ORIENTATIONS.get(rotation));
                break;
        }
        mMediaRecorder.prepare();
    }

    /**
     *  录像
     *  创建MediaRecorder实例 设置录像相关参数
     * 1 创建 MediaRecorder实例  and 用于显示预览图像信息的Surfaced实例
     *
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startRecordingVideo() {
        if (null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {
            return;
        }
        try {
            setUpMediaRecorder();
            SurfaceTexture texture = mTextureView.getSurfaceTexture();
            assert texture != null;
            texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
            //mPreviewRequestBuilder.addTarget()方法 将MediaRecorder 和 Surface的实例添加到请求的目标列表中
            mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
            List<Surface> surfaces = new ArrayList<>();
            // 调用
            // 添加Surface添加预览的View 设置相机的预览
            Surface previewSurface = new Surface(texture);
            surfaces.add(previewSurface);

            mPreviewRequestBuilder.addTarget(previewSurface);

            // 为 mMediaRecorder设置界面
            Surface recorderSurface = mMediaRecorder.getSurface();
            surfaces.add(recorderSurface);
            mPreviewRequestBuilder.addTarget(recorderSurface);

            // 启动捕获会话
            // 一旦会话开始 我们就可以更新UI开始录制了
            mCameraDevice.createCaptureSession(surfaces, new CameraCaptureSession.StateCallback() {

                @Override
                public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                    mPreviewSession = cameraCaptureSession;
                    updatePreview();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                         // UI
                            iv_pictures.setImageDrawable(ContextCompat.getDrawable(getActivity(),R.mipmap.video_stop));
                            mRecordingVideo = 2;
                            // 开始录制
                            mMediaRecorder.start();
                        }
                    });
                }

                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
                    Activity activity = getActivity();
                    if (null != activity) {
                        Toast.makeText(activity, "Failed", Toast.LENGTH_SHORT).show();
                    }
                }
            }, mBackgroundHandler);
        } catch (CameraAccessException | IOException e) {
            e.printStackTrace();
        }

    }

    private void stopRecordingVideo() {
        // UI
//        mRecordingVideo = 3;
        // 停止录像
        mMediaRecorder.stop();
        mMediaRecorder.reset();

        Activity activity = getActivity();
        if (null != activity) {
            Toast.makeText(activity, "Video saved: " + mNextVideoAbsolutePath,
                    Toast.LENGTH_SHORT).show();
            Log.d(TAG, "Video saved: " + mNextVideoAbsolutePath);
        }
        mNextVideoAbsolutePath = null;
        createCameraPreviewSession();
    }


    /**
     * 将JPEG图片保存到指定的File中。
     */
    private class ImageSaver implements Runnable {

        /**
         * JPEG图像
         */
        private final Image mImage;
        /**
         * 我们将图像保存到的文件。
         */
        private final File mFile;

        /**
         * 前后置摄像头切换参数，0：后置， 1：前置。
          */
        private int mCameraState;

        /**
         * 分辨率：0:原始分辨率  1：分辨率1456x1456   2：分辨率480x640   3：分辨率720x1280
         */
        private int mRatio;

        /**
         * 水印标志： 0: 不添加水印   1：添加水印
         */
        private int mWatermark;

        private Context mContext;

        ImageSaver(Image image, File file, int mCameraState, int ratio, int watermark, Context context) {
            mImage = image;
            mFile = file;
            this.mCameraState = mCameraState;
            this.mRatio = ratio;
            this.mWatermark = watermark;
            this.mContext = context;
        }

        @RequiresApi(api = Build.VERSION_CODES.Q)
        @Override
        public void run() {
            ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
            byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);
            int size = 300;
            int pointY = 300;
            FileOutputStream output = null;
            Canvas canvas;
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.length);
            try {
                output = new FileOutputStream(mFile);
                // 前置摄像头水平翻转180
                if(mCameraState == 1){
                    Matrix m = new Matrix();
                    m.postScale(-1,1);
                    bitmap = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),m,true);
                }

                if(mWatermark == 1){  // watermark == 1  加水印
                    Bitmap createBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.RGB_565);
                    if(mCameraState == 1) {
                        canvas = new Canvas(bitmap);
                    }else{
                        canvas = new Canvas(createBitmap);
                    }
                    // 分辨率改变影响到水印大小和位置
                    if(mRatio == 1){
                        size = 72;
                        pointY = 60;
                    }else if(mRatio == 2){
                        size = 32;
                        pointY = 30;
                    }else if(mRatio == 3){
                        size = 64;
                        pointY = 55;
                    }
                    // 加水印
                    canvas.drawBitmap(bitmap, 0, 0, null);
                    Paint paint = new Paint();
                    paint.setStyle(Paint.Style.FILL);
                    paint.setColor(Color.BLUE);
                    paint.setDither(true);
                    paint.setAntiAlias(true);
                    paint.setTextSize(size);
                    canvas.drawText("李前金", 0, pointY, paint);
                    if(mCameraState == 1){
                        bitmap.compress(Bitmap.CompressFormat.JPEG,100, output);
                    }else{
                        createBitmap.compress(Bitmap.CompressFormat.JPEG,100,output);
                    }
                }else {
                    bitmap.compress(Bitmap.CompressFormat.JPEG,100,output);
                }
                System.out.println("======" + mFile.getPath());
//                ImageUtils.insertToDB(mFile, mContext);
                OutputStream outputStream = ImageUtils.insertToDB(bytes, mContext);
                bitmap.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
//获取bitmap缩略图数据
                picture = ThumbnailUtils.extractThumbnail(bitmap, 200, 200);
                begin = System.currentTimeMillis();
                Log.i(TAG, "run: begin "+ begin);
                //发送绘制缩略图消息给Handler
                Message message = new Message();
                message.what = 1;
                pictureHandler.sendMessage(message);
//                ImageUtils.insertToDB(mFile.getAbsolutePath(), mContext);
//                output.write(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                mImage.close();
                if (null != output) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            //获取bitmap缩略图数据
            Bitmap bitmap2 = ThumbnailUtils.extractThumbnail(bitmap, 200, 200);
            picture = bitmap2;
            //发送绘制缩略图消息给Handler
            Message message = new Message();
            message.what = 1;
            pictureHandler.sendMessage(message);
//            mPicture_tv.setImageBitmap(ImageUtils.getLatestThumbBitmap());
        }
    }

    /**
     * 根据两个{@code Size}的面积进行比较。
     */
    static class CompareSizesByArea implements Comparator<Size> {

        @Override
        public int compare(Size lhs, Size rhs) {
            // 我们在这里进行转换以确保乘法不会溢出
            return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
                    (long) rhs.getWidth() * rhs.getHeight());
        }
    }
    private void showMessage(final boolean add, final String message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (add) {
                    textView1.setText(textView1.getText() + "\n" + message);
                } else {
                    textView.setText(message);
                }
            }
        });

    }

    private void runOnUiThread(Runnable runnable) {

    }
}
